package com.kadron.datamodel;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import com.kadron.common.KUtil;
import com.kadron.dao.KNewsDAO;
import com.kadron.entity.News;

public class KNewsModelDataProvider implements KDataProvider {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4707252300895840420L;
	
	private KModelCreator creator;
	private KNewsDAO newsDAO;
	
	public KNewsModelDataProvider(KModelCreator creator, KNewsDAO newsDAO) {
		super();
		this.creator = creator;
		this.newsDAO = newsDAO;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Long> getItemsByRange(Integer integer, int numberOfRows,
			Object object, boolean b) {
		Date moment = KUtil.getMoment();
		EntityManager em = newsDAO.getEntityManager();
		return em.createQuery("SELECT a.id FROM News a WHERE a.start<=:start AND a.end >= :end AND a.active=TRUE")
			.setParameter("start", moment)
			.setParameter("end", moment)
			.setFirstResult(integer)
			.setMaxResults(numberOfRows)
			.getResultList();
	}

	@Override
	public KModel getItemById(Long id, KModelCreator creator) {
		return newsDAO.find(id, News.class);
	}

	@Override
	public int getRowCount() {
		EntityManager em = newsDAO.getEntityManager();
		Date moment = KUtil.getMoment();
		Long count = (Long) em.createQuery("SELECT COUNT(a.id) FROM News a  WHERE a.start<=:start AND a.end >= :end AND a.active=TRUE")
			.setParameter("start", moment)
			.setParameter("end", moment)
			.getSingleResult();
		return (count == null) ? 0 : count.intValue() ;
	}

	@Override
	public boolean hasItemWithId(Long id) {
		return newsDAO.exists(id, News.class);
	}

	@Override
	public KModelCreator getCreator() {
		return creator;
	}

}
